package com.spontaneappnew.fragments;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.spontaneappnew.Categories;
import com.spontaneappnew.FBFriendPlace;
import com.spontaneappnew.Places;
import com.spontaneappnew.R;
import com.spontaneappnew.activities.PlaceProfileActivity;

public class FBFriendTabFragment extends Fragment {
	
	// State
	private FBFriendsFragmentListHandle listHandler;
	
	private static ListView placeList;
	public static ArrayList<FBFriendPlace> places;
	public static PlaceAdapter adapter;
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    	placeList = (ListView)rootView.findViewById(R.id.home_fragment_place_listview);
    	
    	// gets the friend's places list from the singlton
		places = Places.getInstance().getFriendsPlace();
		
		adapter = new PlaceAdapter(getActivity(), places);
		TextView empty = (TextView) rootView.findViewById(R.id.empty_place_list);
		empty.setText("Your Facebook friends haven't added any places in your radius.");
		
		placeList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		placeList.setEmptyView(empty);
		placeList.setAdapter(adapter);
		
		placeList.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(parent.getContext(), PlaceProfileActivity.class);
				Places.getInstance().setCurrentPlace(position, 3);
			    startActivity(intent);
			    getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
			}
		});
        return rootView;
    }

	@Override
    public void onAttach(Activity activity) {
      super.onAttach(activity);
      
      if (activity instanceof FBFriendsFragmentListHandle) {
        listHandler = (FBFriendsFragmentListHandle) activity;
      } else {
        throw new ClassCastException(activity.toString()
            + " must implemenet AllPlacesFragment.fragmentListHandle");
      }
    }
    
  	/**
  	 * Holder class used in the adapter for converView uses.
  	 */
    public class Holder{
		TextView placeName;
		TextView FBFriendName;
		RatingBar rating;
		TextView address;
		TextView distance;
		ImageView categoryIcon;
	}
    
    public class PlaceAdapter extends BaseAdapter{
    	
    	// State
    	private LayoutInflater inflater;
		@SuppressWarnings("unused")
		private Context context;
		private ArrayList<FBFriendPlace> places;
		private String kmOrMile;
		
		// Constructor
		public PlaceAdapter(Context context, ArrayList<FBFriendPlace> places){
			//from is a factory constructor for the layout inflator - default but there's other ways
			this.inflater = LayoutInflater.from(context);
			this.context = context;
			this.places = places;
		}
		
		// Methods
		@Override
		public int getCount() {
			if(places != null)
				return places.size();
			else
				return 0;
		}

		@Override
		public Object getItem(int position) {
			return places.get(position);
		}

		@Override
		//returns the id of the item in my list (if I add things in the beginning of the list that are not being showed I can skip it by adding
		//the right number to position (offset)
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder;
			if(convertView == null){
				convertView = inflater.inflate(R.layout.place_list_row_fb_friend_layout, parent, false);
				holder = new Holder();
				holder.placeName = (TextView)convertView.findViewById(R.id.place_list_item_name_textview);
				holder.FBFriendName = (TextView)convertView.findViewById(R.id.place_list_item_friend_name_textview);
				holder.rating = (RatingBar)convertView.findViewById(R.id.place_list_item_ratingBar);
				holder.address = (TextView)convertView.findViewById(R.id.place_list_item_address_textview);
				holder.distance = (TextView)convertView.findViewById(R.id.place_list_item_distance_textview);
				holder.categoryIcon = (ImageView)convertView.findViewById(R.id.place_list_item_catgory_imageview);
				convertView.setTag(holder);
			}
			else{
				holder = (Holder) convertView.getTag();
			}
			FBFriendPlace currPlace = places.get(position);
			String address = currPlace.getPlace().getStreet()+", " +
					""+currPlace.getPlace().getCity()+", "+currPlace.getPlace().getCountry();
			boolean longName = false;
			boolean longAddr = false;
			int placeNameLen = currPlace.getName().length();
			// make sure the place name in the list will show up to 14
			if(placeNameLen > 20){
				placeNameLen = 20;
				longName = true;
			}
			if(currPlace.getName().substring(0, placeNameLen).contains("\n"))
				placeNameLen = currPlace.getName().indexOf("\n");
			int placeAddressLen = address.length();
			// make sure the place address in the list will show up to 14
			if(placeAddressLen > 30){
				placeAddressLen = 30;
				longAddr = true;
			}
			if(address.substring(0, placeAddressLen).contains("\n"))
				placeNameLen = address.indexOf("\n");
			if(longName)
				holder.placeName.setText(currPlace.getPlace().getName().substring(0, placeNameLen) + "..");
			else
				holder.placeName.setText(currPlace.getPlace().getName());
			holder.FBFriendName.setText("Added by: " + currPlace.getName());
			holder.rating.setRating(currPlace.getPlace().getRating());
			if(longAddr)
				holder.address.setText(address.substring(0, placeAddressLen) + "..");
			else
				holder.address.setText(address);
			kmOrMile = getKMOrMile();
			holder.distance.setText(""+getDistance(currPlace.getPlace().getLocation().getLatitude(), 
					currPlace.getPlace().getLocation().getLongitude()) + kmOrMile);				
			byte[] icon = Categories.getInstance().getCategoryById(currPlace.getPlace().getCategory()).getImage();
			holder.categoryIcon.setImageBitmap(BitmapFactory.decodeByteArray(icon, 0, icon.length));
		
			return convertView;
		}
		
		/*
		 * get km or miles from shared preferences!
		 */
		private String getKMOrMile(){
			if(getActivity().getSharedPreferences("PREF",0).getBoolean("isKm", true))
				return " km";
			else
				return " Miles";
		}
		
		/*
		 * Calculate distance (check for miles or km)
		 */
		private double getDistance(double lat, double lng){
			double dist = listHandler.calculateDistanceFromCurrentLocationInMiles(lat, lng);
			if(getActivity().getSharedPreferences("PREF",0).getBoolean("isKm", true)){
				double meterConversion = 1.6;
				dist *= meterConversion;
			}
			return Math.floor(dist * 10) / 10;
		}
    }
    
    /*
     * the interface for communication with the home activity
     */
    public interface FBFriendsFragmentListHandle {
	    public double calculateDistanceFromCurrentLocationInMiles(double lat, double lng);
	}

}